<template>
    <div>
        <Row>
            <Col span="24">
                <Card dis-hover class="no-border-card">
                    <p slot="title">
                        员工信息
                    </p>
                    <Row :gutter="14" class="yd-padding-b-16">
                        <Col span="8">
                            员工姓名：{{staffInfo.name}}
                        </Col>
                        <Col span="8">
                            员工角色：{{staffInfo.role.name}}
                        </Col>
                        <Col span="8">
                            所属门店：{{branches}}
                        </Col>
                    </Row>
                    <Card dis-hover class="no-border-card">
                        <p slot="title">
                            授权记录
                            <Button class="btn-in-top-large" type="primary" @click="addAcess">添加授权</Button>
                        </p>
                        <Row :gutter="14" class="yd-padding-b-16">
                            <Col span="12" class="staff-access__row" offset="12">
                                <div class="staff-access__item">
                                    <Input v-model.trim="keyword" icon="ios-search-strong" @on-enter="handleSearch" @on-click="handleSearch" placeholder="房源地址/房源编号"></Input>
                                </div>
                            </Col>
                        </Row>
                        <Row style="margin-bottom: 12px;">
                            <Button style="padding:7px 10px 8px;margin-right:12px;">
                                <Checkbox label="全选当页" @on-change="handleSelectAll">
                                    全选当页
                                </Checkbox>
                            </Button>
                            <a href="javascript:void(0);" style="color:green" @click="delRecord(true)">批量取消授权</a>
                        </Row>
                        <Table 
                            @on-selection-change="handleSelect"
                            ref="selection"
                            :loading="tableLoading"
                            :columns="columns"
                            :data="data1"
                            ></Table>
                        <Page   @on-change="getList"
                                :total="total"
                                :page-size="limit" 
                                :current.sync="currentPage"
                                show-elevator 
                                show-total 
                                style="text-align:center"></Page>
                    </Card>
                </Card>
            </Col>
        </Row>
        <Modal
            v-model="isAddModalVisible"
            :loading="true"
            width=750
            title="添加授权">
            <Form ref="addForm" :model="formItem" :label-width="110" >
                <Row :gutter="8">
                    <Col span="9" style="text-align:center">
                        <takePhoto v-model="face_file_id" :isclearPreviewImg="isclearPreviewImg"></takePhoto>
                    </Col>
                    <Col span="15">
                        <FormItem label="员工姓名:">{{staffInfo.name}}</FormItem>
                        <FormItem label="手机号码:">{{staffInfo.telephone}}</FormItem>
                        <FormItem label="所属门店:" prop="branch">
                            <Select v-model="formItem.branch" @on-change="getHome">
                                <Option 
                                    v-for="item in staffInfo.branches"
                                    :value="item.id"
                                    :key="item.id"
                                    >
                                {{item.name}}
                                </Option>
                            </Select>
                        </FormItem>
                        <FormItem label="授权房源:" v-if="isAddModalVisible">
                            <Select
                            :loading="loadingHomes"
                            ref="homes"
                            :remote-method="remoteMethod"
                            clearable
                            filterable
                            placeholder="请选择房源"
                            @on-change="getValue"
                            remote>
                                <Option 
                                v-for="(option, index) in homes"
                                :value="''+option.id"
                                :label = "option.city + option.district + option.address +' (房源编号:'+option.home_name+')'"
                                :key="option.id">{{option.city + option.district + option.address +' (房源编号:'+option.home_name+')'}}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="ghost" size="large" @click='cancel'>取消</Button>
                <Button type="ghost" size="large" @click='addStaffVisit'>确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import { http, api } from '@/libs/http'
import { authState, accessOpstate } from '@/libs/const'
import debounce from 'lodash/debounce'
import takePhoto from '../tenancy-device/take-photo'
export default {
  props: {
    staffInfo: {
      default: {}
    }
  },

  created () {
    this.getList(1)
  },

  data () {
    return {
      store: null,
      loadingHomes: false,
      isAddModalVisible: false,
      keyword: '',
      face_file_id: '',
      isclearPreviewImg: false,
      offset: 0,
      limit: 10,
      tableLoading: false,
      currentPage: 1,
      device_ids: [],
      home_id: '',
      chooseHome: null,
      total: 0,
      formItem: {
        branch: ''
      },
      homes: [],
      selectionInfo: [],
      data1: []
    }
  },
  methods: {
    addAcess () {
      this.isAddModalVisible = true
    },

    handleSearch: debounce(function () {
      this.getList(1)
    }, 300),

    handleSelectAll (status) {
      this.$refs.selection.selectAll(status)
    },
    // 删除授权，flag代表批量删除
    delRecord (flag, param) {
      let auth_ids = []
      if (flag && this.selectionInfo.length === 0) {
        this.$Message.error('请添加取消授权')
        return
      }
      if (flag) {
        auth_ids = this.selection
      } else {
        auth_ids.push(param.row.id)
      }
      const params = {
        auth_ids: auth_ids
      }
      http.request(this, api.face_access_del, [this.staffInfo.id], params, (res, err) => {
        if (err || !res) {
          return
        }
        this.getList(1)
        this.$Message.info('删除指令下发成功')
      })
    },

    getHome (value) {
      this.branch_id = value
    },

    getValue (value) {
      this.getDeviceIds(value)
      this.home_id = value
    },

    handleSelect (selection) {
      this.selectionInfo = selection
      selection = selection.map(item => {
        return item.id
      })
      this.selection = selection
    },

    getDeviceIds (home_id) {
      if (!home_id) return
      http.request(this, api.face_access_of_home, [home_id], null, (res, err) => {
        if (err || !res) {
          return
        }
        this.device_ids = res.map((item) => (item.id))
      })
    },
    addStaffVisit: debounce(function () {
      this.addStaffVisitPre()
    }, 300),
    async addStaffVisitPre () {
      if (!this.face_file_id) {
        this.$Message.error('门禁授权必须拍照')
        return
      }
      if (!this.branch_id) {
        this.$Message.error('请选择门店!')
        return
      }
      if (!this.home_id) {
        this.$Message.error('请选择房源')
        return
      }
      if (this.device_ids.length === 0) {
        this.$Message.error('此房源没有门禁')
        return
      }
      if (!this.home_id) {
        this.$Message.error('授权房源不能为空')
        return
      }

      try {
        const params = {
          face_file_id: this.face_file_id,
          relation_role: 1,
          relation_id: this.staffInfo.id,
          device_ids: this.device_ids,
          auth_start_time: new Date().getTime(),
          auth_end_time: new Date('2300-10-30').getTime()
        }

        await http.fetch(this, api.face_access_add, [this.home_id], params)
        this.cancel()
        this.getList(1)
        this.$Message.success('门禁授权指令下发成功')
      } catch (error) {
        console.log('error', error)
      }
    },

    getList (page) {
      let params = {
        keyword: this.keyword ? this.keyword : null,
        limit: this.limit,
        offset: this.limit * (page - 1)
      }
      let id = this.staffInfo.id
      if (page === 1) {
        this.currentPage = 1
      }

      this.tableLoading = true
      http.request(this, api.user_auth_list, [id], params, (res, err) => {
        this.tableLoading = false
        if (err || !res) {
          return
        }
        this.data1 = res.rows
        this.total = res.count
        this.setDisableSelect(this.data1)
      })
    },

    setDisableSelect (data) {
      const disableSelectState = [11, 21, 31, 33]
      data.forEach(item => {
        if (disableSelectState.includes(item.op_state)) {
          item._disabled = true
        }
      })
    },

    cancel () {
      this.isAddModalVisible = false
      this.reset()
    },

    reset () {
      this.$refs['addForm'].resetFields()
      this.$refs['homes'].clearSingleSelect()
      this.device_ids = []
      this.home_id = ''
      this.face_file_id = ''
    },

    remoteMethod (query) {
      if (!this.branch_id) {
        this.$Message.error('请先选择门店!')
        return
      }
      let branch_id = this.branch_id !== -1 ? this.branch_id : null
      // 搜索房源
      if (query !== '') {
        let params = {
          keyword: query,
          branch_id: branch_id
        }
        this.loadingHome = true
        http.request(this, api.home_list, null, params, res => {
          if (res) {
            this.homes = res.homes
          }
          this.loadingHome = false
        })
      } else {
        this.homes = []
      }
    }
  },
  components: {
    takePhoto
  },
  watch: {
    $route (n) {
      if (n) {
        this.$store.dispatch('setCurrentTab', '/' + (this.$route.params.staffId || ''))
      }
    }
  },
  computed: {
    branches () {
      let branches = ''
      if (this.staffInfo.branches.length === 0) {
        this.staffInfo.branches.push({'name': '总部', 'id': -1})
      }
      this.staffInfo.branches.forEach((item, index) => {
        if (index === 0) {
          branches = branches + item.name
        } else {
          branches = branches + '、' + item.name
        }
      })
      return branches
    },
    // 预防以后要加权限。
    columns () {
      const data = [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '所在城市',
          key: 'city',
          align: 'center'
        },
        {
          title: '授权房源',
          key: 'home_name',
          align: 'center',
          render: (h, params) => {
            return (
              <span>
                { params.row.city + params.row.district + params.row.home_address + '( 房源编号:' + params.row.home_name + ' )' }
              </span>
            )
          }
        },
        {
          title: '房间',
          key: 'room_name',
          align: 'center'
        },
        {
          title: '门禁',
          key: 'device_name',
          align: 'center'
        },
        {
          title: '授权状态',
          key: 'auth_state',
          align: 'center',
          render: (h, params) => {
            return (
              <span>
                {authState[params.row.auth_state]}
              </span>
            )
          }
        },
        {
          title: '备注',
          key: 'op_state',
          align: 'center',
          render: (h, params) => {
            return (
              <span>
                {accessOpstate[params.row.op_state]}
              </span>
            )
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 260,
          align: 'center',
          render: (h, params) => {
            const base = {
              props: {
                type: 'ghost',
                size: 'small'
              }
            }
            if (![11, 21, 31, 33].includes(params.row.op_state)) {
              return (
                <div>
                  <i-button
                    {...base}
                    onClick={() => this.delRecord(false, params)}>
                                        取消授权
                  </i-button>
                </div>
              )
            }
          }
        }
      ]
      return data
    }
  }
}
</script>

<style lang="less">
.yd-padding-b-16 {
    padding-bottom: 16px;
}
.staff-access{
    &__search{
        margin: 20px 0;
        padding: 20px;
        background-color: snow;
    }
    &__row{
        display: flex;
        align-items: center;
    }

    &__label{
        margin-right: 5px;
    }

    &__item{
        flex: 1;
    }

    &__label--width{
        display:inline-block;
        width: 110px;
    }
}
</style>
